package LintCode;

import java.util.Arrays;

/**
 * @Classname SquaresOfASortedArray
 * @Description TODO
 * @Date 2021/3/3 10:23
 * @Created by ASUS
 */
public class SquaresOfASortedArray {

    /**
     * @param A: The array A.
     * @return The array of the squares.
     */
    public int[] SquareArray(int[] A) {
        // my answer code
        if (A == null || A.length == 0) return A;// jude the array.
        if (A[0] >= 0 || A.length == 1) {
            for (int i = 0; i < A.length; i++) A[i] *= A[i];
            return A;
        }
        int[] res = new int[A.length];
        int i = 0, j = A.length - 1, index = j;
        while (i < j) {
            int left = A[i] * A[i];
            int right = A[j] * A[j];
            res[index--] = Math.max(left, right);
            if (left < right) j--;
            else i++;
        }
        res[index] = A[i] * A[i];


        return res;

    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new SquaresOfASortedArray().SquareArray(new int[]{-112, -45, -4, -1, 0, 83, 110})));
    }
}
